import reportData from "./report-data";
import { replaceAop } from "./xhr-AOP";
function promiseAOP() {
  if (!("fetch" in window)) return;

  replaceAop(window, "fetch", (originalFetch) => {
    return function (url, config) {
      const sTime = new Date().getTime();
      const method = (config && config.method) || "GET";
      let handlerData = {
        type: "fetch",
        method,
        reqData: config && config.body,
        url,
      };

      return originalFetch.apply(window, [url, config]).then(
        (res) => {
          // res.clone克隆，防止被标记已消费
          const tempRes = res.clone();
          const eTime = new Date().getTime();
          handlerData = {
            ...handlerData,
            elapsedTime: eTime - sTime,
            status: tempRes.status,
          };
          tempRes.text().then((data) => {
            handlerData.responseText = data;
            reportData(handlerData);
          });
          // 返回原始结果，外部继续使用then接收
          return res;
        },
        (err) => {
          handlerData = {
            ...handlerData,
            elapsedTime: eTime - sTime,
            status: 0,
          };

          reportData(handlerData);
          throw err;
        }
      );
    };
  });
}

export default promiseAOP;
